package com.itheima.gatewaywemedia.filters;

import cn.hutool.core.util.StrUtil;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.gatewaywemedia.filters
 */
@Component
@Slf4j
public class WemediaAuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求、响应对象
        ServerHttpRequest req = exchange.getRequest();
        ServerHttpResponse res = exchange.getResponse();
        //2. 获取请求路径
        String path = req.getURI().getPath();
        log.info("请求了路径: {}", path);
        //3. 白名单(登录请求)放行判断
        if (path.endsWith("/login/in")) {
            return chain.filter(exchange);
        }
        //4. 获取请求头中的token
        String token = req.getHeaders().getFirst("token");
        //5. 校验token有效性，有效则放行
        if (StrUtil.isNotEmpty(token)) {
            int verifyToken = 0;
            //verifyToken = AppJwtUtil.verifyToken(token);
            try {
                // 解析token后获得了 得到载荷
                Claims claims = AppJwtUtil.getClaimsBody(token);
                //获取载荷中的登录用户id
                Long loginUserId = claims.get("id", Long.class);
                // 存入请求头
                req.mutate().header(SystemConstants.USER_HEADER_NAME, loginUserId.toString());
                return chain.filter(exchange);
            } catch (ExpiredJwtException ex) {
                log.error("token已过期!", ex);
            } catch (Exception e) {
                log.error("非法token",e);
            }
        }
        //6. 响应401
        res.setStatusCode(HttpStatus.UNAUTHORIZED);
        return res.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
